// 1. 引入依赖
const multer = require('multer');
const md5 = require('md5');
// 2. 引入工具
const path = require('path') //
const fs = require('fs')
const resolve = (dir) => {
    return path.join(__dirname, './', dir)
}
const callback = () => {
    console.log("文件目录处理失败");
}
// 3. multer的配置对象
let storage = multer.diskStorage({
    // 3.1 存储路径
    destination: function (req, file, cb) {
        let email = req.auth.email
        let filePath = resolve(`../public/images/${email}/`)
        let isexist = isexistsSync(filePath)
        if (isexist) {
            // 3.1.1 允许图片上传
            if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'image/jpg') {
                cb(null, resolve(`../public/images/${email}/`))
            } else {
                // 3.1.2 限制其他文件上传类型
                cb({ error: 'Mime type not supported' })
            }
        }
    },
    //  3.2 存储名称
    filename: function (req, file, cb) {
        let fileFormat = (file.originalname).split(".");
        cb(null, md5(+new Date()) + "." + fileFormat[fileFormat.length - 1]);
    },
});

// 4. 添加配置
const multerConfig = multer({
    storage: storage,
});
//判断路径是否存在
function isexistsSync(filePath) {
    if (fs.existsSync(filePath)) {
        console.log('该路径已存在');
        return true
    } else {
        console.log('该路径不存在');
        return mkdirs(filePath, callback)
    }
}
//创建路径
function mkdirs(dirname, callback) {
    //异步方法
    /* fs.access(dirname, function (exists) {
            if (!exists) {
                callback();
            } else {
                mkdirs(path.dirname(dirname), function () {
                    fs.mkdir(dirname, callback);
                    console.log('在' + path.dirname(dirname) + '目录创建好' + dirname + '目录');
                    return true
                });
            }
        }); */
    //同步方法
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirs(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            console.log('在' + path.dirname(dirname) + '目录创建好' + dirname + '目录');
            return true;
        }
    }
}

// 5. 导出配置好的multerConfig
module.exports = multerConfig;